<!--
 抛出事件
 updateList：执行查询
 upda¬¬teFilter：勾选或取消勾选某个筛选器或更新一个旧的筛选器
 renameFilter：重命名筛选器
 createNew：新建筛选器
 deleteFilterById：删除筛选器
 -->
<template>
  <div style="position: relative">
    <el-tabs v-model="editableTabsValue"
             :closable="selectedTabs.length > 1"
             @tab-click="tabClick"
             @edit="handleTabsEdit">
      <el-tab-pane v-for="tab of selectedTabs" :key="tab.id" :label="tab.title" :name="tab.id">
        <div v-show="conditionShow">
          <div style="width: 100%; position: relative">
            <el-form :inline="true" :model="filterConditions" :label-width="`${labelWidth}px`" size="small">
              <el-row :gutter="2" style="display: flex; flex-wrap: wrap">
                <!-- 查询字段，由插槽传递 -->
                <slot name="fields" :selectedCondition="selectedCondition" :filterConditions="filterConditions" />
                <div style="width:108px">
                  <!--查询-->
                  <el-button type="primary" @click="handleSearch">查询</el-button>
                  <el-button @click="handleReset">重置</el-button>
                </div>
              </el-row>
              <!--编辑筛选条件-->
              <div style="margin-top:10px;">
                <el-popover v-if="canSaveFilter" placement="bottom" width="120" trigger="click">
                  <ul class="filterSelect">
                    <li v-for="(item, index) in bugFilterInfo.FILTERS" :key="index">
                      <el-checkbox v-model="item.show"
                                   :label="item.label"
                                   size="small"
                                   @change="
                                     (checked:boolean) => {
                                       updateItem(index, checked);
                                     }
                                   ">
                        {{ item.label }}
                      </el-checkbox>
                    </li>
                  </ul>
                  <template #reference>
                    <span class="el-dropdown-link"
                          style="font-size: 12px;color:rgb(64, 158, 255);margin-right:5px;cursor:pointer;">
                      编辑筛选条件
                    </span>
                  </template>
                </el-popover>
                <el-button v-if="tabPane.isSystem === 0 && canSaveFilter" @click="saveFilter">保存</el-button>
                <el-button v-if="canSaveFilter" @click="saveAsFilter">另存为</el-button>
              </div>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div class="buttonArea">
      <el-popover v-if="canSaveFilter" placement="bottom" width="170" trigger="click">
        <div style="max-height: 80vh; overflow: auto">
          <!-- 系统筛选器 -->
          <ul class="jacp-setting-fields">
            <li v-for="item in systemTabs" :key="item.id">
              <el-checkbox v-model="item.select"
                           :label="item.title"
                           :disabled="canChange(item)"
                           @change="
                             (checked: boolean) => {
                               updateSelectedTabs(checked, item);
                             }
                           ">
                {{ item.title }}
              </el-checkbox>
            </li>
          </ul>
          <div class="border-top">保存的筛选器</div>
          <!-- //自定义筛选器 -->
          <ul class="jacp-setting-fields">
            <li v-for="item in definedTabs" :key="item.id">
              <el-checkbox v-model="item.select"
                           :label="item.title"
                           :disabled="canChange(item)"
                           @change="
                             (checked: boolean) => {
                               updateSelectedTabs(checked, item);
                             }
                           ">
                <span class="chk" :title="item.title">{{ item.title }}</span>
              </el-checkbox>
              <el-popover placement="right-start" width="20" :visible-arrow="false" trigger="hover">
                <el-button size="small" link type="primary" @click="renameFilter(item)">重命名
                </el-button>
                <br />
                <el-button size="small" link type="primary" :disabled="canChange(item)" @click="deleteFilter(item.id)">删除
                </el-button>
                <template #reference>
                  <el-icon style="float: right; margin: 11px auto">
                    <MoreFilled />
                  </el-icon>
                </template>
              </el-popover>
            </li>
          </ul>
          <div class="border-top">
            <el-button type="primary" size="small" @click="addTab()"><el-icon style="margin-right:10px;">
              <Plus />
            </el-icon>
              新增筛选器
            </el-button>
          </div>
        </div>
        <template #reference>
          <span class="el-dropdown-link" style="margin-right: 12px; font-size: 14px; color: #778899">
            更多
            <el-icon>
              <CaretBottom />
            </el-icon>
          </span>
        </template>
      </el-popover>
      <div class="el-dropdown-link" style="display:flex;align-items:center">
        <el-icon @click="changeFilter" style="margin-right:10px">
          <ArrowUp v-if="conditionShow" />
          <ArrowDown v-else />
        </el-icon>
        <slot name="outerAction" />
      </div>
    </div>
    <el-dialog title="筛选器名称"
               v-model="showSetName"
               :append-to-body="false"
               width="350px"
               @close="handleCloseFilterNameDialog">
      <el-form ref="formName" :model="form" :rules="rules">
        <el-form-item prop="filterName" label="筛选器名称">
          <el-input v-show="false" placeholder="防止回车导致页面加载" />
          <el-input ref="filterNameDom"
                    v-model="form.filterName"
                    autocomplete="off"
                    clearable
                    maxlength="20"
                    show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="
            () => {
              changeShowSetName(false);
            }
          ">取 消</el-button>
          <el-button type="primary" @click="confirmSave">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import __ from 'lodash'
import { pushData, readData, updateData } from '@/tools/indexDB'
import { onBeforeMount, reactive, ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { Filter, Attr, TabPane, SelectedTab, Props, FilterDB } from './interface'
import type { FormInstance, InputInstance, TabsPaneContext } from 'element-plus'
function displayStorage(key: string): boolean {
  return JSON.parse(localStorage.getItem(key) as string)
}
const props = defineProps<Props>()
// 校验筛选器名称
const validateName = (rule: any, value: string, callback: Function) => {
  const isEmpty = value === ''
  const containBlank = !/^[^\s]*$/.test(value)
  let isExist
  if (renameId.value > 0) {
    // 重命名筛选器
    isExist = currentFilters.reduce(
      (res, cur: any) =>
        cur.filterName === value && cur.id !== renameId.value ? true : res,
      false
    )
  } else {
    // 新建筛选器
    isExist = currentFilters.reduce(
      (res, cur: any) => (cur.filterName === value ? true : res),
      false
    )
  }
  if (isEmpty || containBlank || isExist) {
    const message = isEmpty
      ? '请输入筛选器名称'
      : containBlank
        ? '筛选器名称不能有空格'
        : '筛选器名称重复'
    callback(new Error(message))
  } else {
    callback()
  }
}
function initForm() {
  const mid: any = {}
  props.defaultAttr.FILTERS.forEach((item: any) => {
    mid[item.key] = item.isArray ? [] : ''
  })
  return mid
}
// 初始化表单数据
const editableTabsValue = ref(0) // 当前筛选器id
const selectedTabs = reactive<SelectedTab[]>([]) // 选中在标签页展示的筛选器
const definedTabs = reactive<SelectedTab[]>([]) // 自定义筛选器
const systemTabs = reactive<SelectedTab[]>([]) // 系统筛选器
const showSetName = ref(false) // 是否显示设置筛选器名称弹窗
const selectedCondition = ref<Attr[]>([]) // 展示的字段
const bugFilterInfo = reactive(__.cloneDeep(props.defaultAttr)) // 深拷贝默认筛选项
const filterConditions = reactive(initForm()) // 筛选条件表单
const unNamed = ref('未命名') // 新增筛选器默认名称
let currentFilters:Filter[] = [] // 深拷贝所有筛选器
const tabIndex = ref(1) // 新增筛选器名称后缀
const conditionShow = ref(true) // 筛选项展开与收起
let dbData: FilterDB // 从数据库中读取的筛选器数据
const keyLabel:{[key:string]:string} = {} // 筛选项key与label映射

// 保存数据库
const saveDb = () => {
  return new Promise((resolve, reject) => {
    updateData('filters', 'index', props.filterType, dbData).then(() => {
      resolve('success')
    }).catch(() => {
      reject()
    })
  })
}

// 筛选器命名部分
const renameId = ref(0) // 重命名的筛选器id
const form = reactive({ filterName: '' }) // 筛选器名称表单
const formName = ref<FormInstance>()
const filterNameDom = ref<InputInstance>()
const rules = {
  filterName: [
    { required: true, message: '请输入筛选器名称', trigger: 'blur' },
    { validator: validateName, trigger: 'change' }
  ]
}
function changeShowSetName(val: boolean) {
  showSetName.value = val
  if (val) {
    nextTick(() => {
      setTimeout(() => {
        (filterNameDom.value as InputInstance).focus()
      }, 0)
    })
  }
}
function handleCloseFilterNameDialog() {
  setTimeout(() => {
    (formName.value as FormInstance).resetFields()
    renameId.value = 0
  }, 300)
}
function confirmSave() {
  (formName.value as FormInstance).validate((valid: boolean) => {
    if (!valid) {
      return
    }
    if (renameId.value === 0) {
      // 新建
      const { filterName: name } = form
      changeShowSetName(false)
      const params = {
        id: 0,
        isSystem: 0,
        filterName: name,
        filterAttrs: bugFilterInfo.FILTERS.map((filter: Attr) => ({
          label: filter.label,
          key: filter.key,
          show: filter.show,
          value: JSON.parse(JSON.stringify(filterConditions[filter.key]))
        })),
        selected: tabPane.value.id < 0 ? 1 : 0,
        filterType: props.filterType
      }
      if (props.isSaveLocal) {
        // 保存本地
        saveNewFilterToDataBase(params)
      } else {
        // 抛给父组件执行
        $emit('createNew', params, 'afterCreateNew')
      }
    } else {
      // 重命名筛选器
      renameConfirm()
    }
  })
}
async function renameConfirm() {
  if (props.isSaveLocal) {
    dbData.data.forEach(item => {
      if (item.id === renameId.value) {
        item.filterName = form.filterName
      }
    })
    await saveDb()
    afterRename((dbData.data.find((item:Filter) => item.id === renameId.value) as Filter))
  } else {
    $emit('renameFilter', renameId.value, {
      filterName: form.filterName
    })
  }
}
// 这里需由父组件调用
function afterRename(res: Filter) {
  definedTabs.forEach((f) => {
    if (f.id === res.id) {
      f.title = res.filterName
    }
  })
  selectedTabs.forEach((f) => {
    if (f.id === res.id) {
      f.title = res.filterName
    }
  })
  // if (res.defaulted === 1) {
  //   editableTabsValue.value = res.id
  // }
  currentFilters.forEach((item) => {
    if (item.id === res.id) {
      item.filterName = res.filterName
    }
  })
  successMsg('操作成功！')
  changeShowSetName(false)
}
async function saveNewFilterToDataBase(params: Filter) {
  // TODO先拿数据库数据
  const id = dbData.data.reduce((res: number, { id }: Filter) => (id > res ? id : res), 0)
  const newFilter = { ...params, id: id + 1 }
  dbData.data.push(newFilter)
  await saveDb()
  afterCreateNew(newFilter)
}
function afterCreateNew(res: Filter) {
  currentFilters.push(res)
  successMsg('操作成功！')
  const { filterName: title, id, isSystem, selected } = res
  const obj: SelectedTab = {
    title,
    id,
    isSystem,
    select: getVal(selected)
  }
  definedTabs.push(obj)
  if (editableTabsValue.value < 0) {
    // 新增筛选器并保存
    selectedTabs.forEach((tab) => {
      if (editableTabsValue.value === tab.id) {
        editableTabsValue.value = tab.id = id
        tab.title = title
        tab.isSystem = isSystem
        tab.select = getVal(selected)
      }
    })
  }
}

const $emit = defineEmits(['updateList', 'updateFilter', 'createNew', 'deleteFilterById', 'renameFilter'])
// 当前活跃的筛选器
const tabPane = computed<TabPane>(() => {
  return selectedTabs.reduce(
    (res, cur: SelectedTab) => (cur.id === editableTabsValue.value ? cur : res),
    {} as TabPane
  )
})
watch(() => props.defaultAttr.FILTERS, (val: Attr[]) => {
  val.forEach(item => { keyLabel[item.key] = item.label as string })
}, { immediate: true })
watch(() => props.filterArr, async(val: Filter[]) => {
  if (!val.length) {
    return
  }
  // 从indexDB中读取数据
  if (props.isSaveLocal) {
    const res = (await readData('filters', 'index', props.filterType)) as FilterDB
    if (res) {
      // 数据库中有值,用传进来的值替换进行替换
      res.data = synchronize(res.data, val)
      conditionShow.value = res.conditionShow
      dbData = res
      init(__.cloneDeep(res.data))
      // 更新数据库
      saveDb()
    } else {
      dbData = { name: props.filterType, data: val, conditionShow: conditionShow.value }
      pushData('filters', 'index', dbData)
      init(__.cloneDeep(val))
    }
  } else {
    init(__.cloneDeep(val))
  }
}, { immediate: true })
onBeforeMount(() => {
  if (!props.isSaveLocal) {
    const mid = displayStorage(props.filterType)
    conditionShow.value = displayStorage(props.filterType) === null ? conditionShow.value : mid
  }
})
// 同步传进来的筛选器到数据库中
function synchronize(db: Filter[], out: Filter[]) {
  // 替换或添加
  out.forEach(item => {
    const index = db.findIndex(sub => sub.id === item.id)
    if (index > -1) {
      db[index].filterAttrs = item.filterAttrs
    } else {
      db.unshift(item)
    }
  })
  // 更新
  const mid = props.defaultAttr.FILTERS
  db.forEach(item => {
    if (!out.some(sub => sub.id === item.id)) {
      item.filterAttrs = item.filterAttrs?.reduce((res: Attr[], { key, show, value }: Attr) => {
        const son = mid.find(newAttr => newAttr.key === key)
        if (son) {
          return [...res, { key, show, value }]
        } else {
          return res
        }
      }, [])
      mid.forEach(sub => {
        if (!item.filterAttrs?.some(tij => tij.key === sub.key)) {
          item.filterAttrs?.push({ ...sub, value: [] })
        }
      })
    }
  })
  return db
}

function tabClick(tab?: TabsPaneContext) {
  selectedCondition.value = []
  if (tabPane.value.id < 0) {
    const mid: Attr[] = []
    // 新增筛选器
    props.defaultAttr.FILTERS.forEach((filter: Attr) => {
      const { show, key } = filter
      if (show) {
        mid.push(filter)
      }
      // 给筛选器下拉框中显示与否赋值
      updateBugFilterInfo(filter)
      // 给筛选条件赋值
      filterConditions[key] = checkType(key) ? [] : ''
    })
    selectedCondition.value = mid
  } else {
    // 自定义、系统
    const id = tab ? tab.props.name : tabPane.value.id
    const mid: Filter = currentFilters.filter(
      (f: Filter) => f.id === id
    )[0]
    mid.filterAttrs?.forEach((attr: Attr) => {
      // 给筛选条件赋值
      setConditionValue(attr)
      // 给筛选器下拉框中显示与否赋值
      updateBugFilterInfo(attr)
      // 筛选器条件是否显示在页面
      pushSelectedCondition(attr)
    })
    nextTick(() => {
      dbData.data.forEach((item: Filter) => {
        if (item.id === editableTabsValue.value) {
          item.isCurrent = true
        } else {
          item.isCurrent = false
        }
      })
      saveDb()
    })
  }
  handleSubmit()
}
function updateBugFilterInfo(attr: Attr) {
  bugFilterInfo.FILTERS.forEach((f: Attr) => {
    if (attr.key === f.key) {
      f.show = attr.show
    }
  })
}
function setConditionValue(attr: Attr) {
  const { key, value } = attr
  filterConditions[key] = checkType(key) ? value : (value?.[0] ?? '')
}
function checkType(key: string) {
  return props.defaultAttr.FILTERS.reduce(
    (res: boolean, cur: any) => (cur.key === key ? cur.isArray : res),
    false
  )
}
function pushSelectedCondition(attr: any) {
  const { key, show } = attr
  if (show) {
    selectedCondition.value.push({ key, label: keyLabel[key], show })
  }
}
// 查询
function handleSubmit(val:boolean = false) {
  storageFilter()
  const mid:{[key:string]:any} = {}
  for (const key in filterConditions) {
    if (String(filterConditions[key])?.length) {
      mid[key] = filterConditions[key]
    }
  }
  $emit(
    'updateList',
    __.cloneDeep(mid),
    tabPane.value.title,
    val,
    currentFilters
  )
}
// 手动点击查询按钮
function handleSearch() {
  handleSubmit(true)
}
// 缓存筛选条件
function storageFilter() {
  setTimeout(() => {
    currentFilters.forEach((item: Filter) => {
      if (item.id === editableTabsValue.value) {
        item.isCurrent = true
        item.filterAttrs?.forEach((sub: Attr) => {
          sub.show = selectedCondition.value.some(
            (mid) => mid.key === sub.key
          )
          const value = filterConditions[sub.key]
          sub.value = Array.isArray(value)
            ? value
            : String(value).length
              ? [value]
              : []
        })
      } else {
        item.isCurrent = false
      }
    })
  }, 300)
}
// function changeCandidataValues(title: string, key: string, validate: any) {
//   currentFilters.forEach((item: any) => {
//     if (item.filterName === title) {
//       item.filterAttrs.forEach((sub: any) => {
//         if (sub.key === key) {
//           sub.candidataValues = validate
//         }
//       })
//     }
//   })
// }
function handleTabsEdit(targetId: number) {
  // 数据减少一个
  const findIndex = selectedTabs.findIndex(
    (sub: SelectedTab) => sub.id === targetId
  )
  selectedTabs.splice(findIndex, 1)

  // 删除的为当前活跃的tab
  if (editableTabsValue.value === targetId) {
    const nextTab: SelectedTab = selectedTabs[0]
    const activeId = nextTab.id
    editableTabsValue.value = activeId
    tabClick() // 删除后，还需要再调查询接口
  }

  // 数据存储
  if (targetId > 0) {
    // 删除的不是新增未保存的
    updateFilterSelected(targetId, 0)
  }

  // 更新自定义数据和系统数据
  definedTabs.forEach((tab) => {
    if (tab.id === targetId) {
      tab.select = false
    }
  })
  systemTabs.forEach((tab) => {
    if (tab.id === targetId) {
      tab.select = false
    }
  })
}
// 选中或删除某个筛选器
function updateFilterSelected(itemId: number, selected: number) {
  // 这里需抛给父组件执行，仅选中或取消
  if (!props.isSaveLocal) {
    $emit(
      'updateFilter',
      {
        id: currentFilters.find((filter: Filter) => filter.id === itemId)?.id,
        selected
      },
      'afterUpdateFilter'
    )
  } else {
    dbData.data.forEach((item: Filter) => {
      if (item.id === itemId) {
        item.selected = selected
      }
    })
    saveDb()
  }
}
// 这里需由父组件调用
// function afterUpdateFilter(res: any) {
//   currentFilters.forEach((f: any) => {
//     if (f.id === String(res.id)) {
//       f.selected = res.selected
//     }
//   })
// }
function updateItem(index: number, checked: boolean) {
  const item = bugFilterInfo.FILTERS[index]
  item.show = checked
  if (checked) {
    selectedCondition.value.push(item)
  } else {
    // 删除筛选条件
    filterConditions[item.key] = checkType(item.key)
      ? []
      : ''
    nextTick(() => {
      deleteItem(selectedCondition.value, item.key)
    })
  }
}
function deleteItem(deleteList: any, key: string) {
  const i = deleteList.reduce(
    (res: number, cur: any, index: number) => (key === cur.key ? index : res),
    -1
  )
  deleteList.splice(i, 1)
}
// 保存筛选器
async function saveFilter() {
  const { id, title: filterName } = tabPane.value
  if (id <= 0) {
    // 新增的筛选器保存
    form.filterName = ''
    changeShowSetName(true)
  } else {
    // 更新一个旧的筛选器
    const params = {
      filterName,
      id,
      filterAttrs: bugFilterInfo.FILTERS.map((filter) => {
        const { label, key, show } = filter
        const value = JSON.parse(JSON.stringify(filterConditions[key]))
        return (
          {
            label,
            key,
            show,
            value: Array.isArray(value) ? value : [value]
          })
      }),
      isSystem: 0,
      selected: 1
    }
    if (props.isSaveLocal) {
      const targetFilter = dbData.data.find(item => item.id === id) as Filter
      targetFilter.filterAttrs = params.filterAttrs
      targetFilter.selected = 1
      targetFilter.isCurrent = true
      await saveDb()
      afterUpdateOld(targetFilter)
    } else {
      $emit(
        'updateFilter',
        params,
        'afterUpdateOld'
      )
    }
  }
}
// 这里需由父组件调用
function afterUpdateOld(res: Filter) {
  successMsg('操作成功！')
  pushOrReplace(currentFilters, res)
}
function successMsg(msg: string) {
  ElMessage({
    message: msg,
    type: 'success'
  })
}
// 数组添加或替换
function pushOrReplace(arr: any, val: any) {
  const index = arr.findIndex((item: any) => item.id === val.id)
  if (index === -1) {
    arr.push(val)
  } else {
    arr.splice(index, 1, val)
  }
}
// 另存为
function saveAsFilter() {
  form.filterName = ''
  changeShowSetName(true)
}
function handleReset() {
  props.defaultAttr.FILTERS.forEach(item => {
    const { isArray, key } = item
    filterConditions[key] = isArray ? [] : ''
  })
  handleSubmit()
}
function updateSelectedTabs(checked: boolean, item: SelectedTab) {
  if (checked) {
    // 选中
    if (!controlFilterNum()) {
      nextTick(() => {
        definedTabs.forEach((sub) => {
          if (sub.id === item.id) {
            sub.select = false
          }
        })
        systemTabs.forEach((sub) => {
          if (sub.id === item.id) {
            sub.select = false
          }
        })
      })
      return
    }
    selectedTabs.push(item)
    // 同时更新后台数据
    updateFilterSelected(item.id, 1)
  } else {
    // 取消选中
    deletedData(selectedTabs, item.id)
  }
}
// 筛选器数量控制
function controlFilterNum() {
  if (selectedTabs.length >= props.maxTab) {
    warning(`页面最多展示${props.maxTab}个tab页,可删除后进行操作`)
    return false
  } else {
    return true
  }
}
function warning(msg: string) {
  ElMessage({
    message: msg,
    type: 'warning'
  })
}
function deletedData(deleteList: any, id: number) {
  const activeId = editableTabsValue.value // 活动活动的tab
  const findIndex = deleteList.findIndex((item: any) => item.id === id)
  if (findIndex === -1) {
    return
  }
  // 同时更新后台筛选器信息
  updateFilterSelected(id, 0)
  deleteList.splice(findIndex, 1)
  if (activeId !== id) {
    return
  }
  const nextTab =
    deleteList[findIndex - 1] || deleteList[findIndex + 1] || deleteList[0]
  editableTabsValue.value = nextTab.id
  nextTick(() => {
    tabClick() // 删除当前tab后，还需要再调查询接口
  })
}

function init(arr: Filter[]) {
  // 赋值
  currentFilters = arr
  arr.forEach((filter: Filter) => {
    queryOneFilter(filter)
  })
  if (selectedTabs.length === 0) {
    // 保证至少有一个活跃tab
    systemTabs[0].select = true
    selectedTabs.push(systemTabs[0])
  }
  // 设置默认生效的筛选器
  editableTabsValue.value = selectedTabs.reduce((res:number, cur:SelectedTab) => cur.isCurrent ? cur.id : res, selectedTabs[0].id)
  nextTick(() => {
    tabClick()
  })
}
function queryOneFilter(filter: Filter) {
  const { id, filterName, selected, isSystem, isCurrent } = filter
  const obj = {
    id,
    title: filterName,
    select: selected === 1,
    isSystem,
    isCurrent
  }
  if (isSystem === 0) {
    // 自定义筛选器
    pushOrReplace(definedTabs, obj)
  } else {
    // 系统筛选器
    pushOrReplace(systemTabs, obj)
  }
  if (selected === 1) {
    // 被选中在tab标签显示的筛选器
    pushOrReplace(selectedTabs, obj)
  }
}
// 点击新增筛选器
function addTab() {
  if (!controlFilterNum()) {
    return
  }
  conditionShow.value = true // 默认展开筛选条件
  const newTabName = `${unNamed.value}${tabIndex.value++}`
  const uuid = -Date.now()
  selectedTabs.push({
    id: uuid,
    title: newTabName,
    select: true,
    isSystem: 0
  })
  editableTabsValue.value = uuid
  tabClick()
}
function canChange(item: SelectedTab) {
  if (
    item.select &&
    selectedTabs.length === 1 &&
    item.id === editableTabsValue.value
  ) {
    return true
  } else {
    return false
  }
}
function renameFilter(item: SelectedTab) {
  renameId.value = item.id
  form.filterName = item.title
  changeShowSetName(true)
}
async function deleteFilter(filterId: number) {
  if (props.isSaveLocal) {
    dbData.data = dbData.data.filter(item => item.id !== filterId)
    await saveDb()
    afterDelFilter(filterId)
  } else {
    $emit('deleteFilterById', filterId)
  }
}
// 这里需由父组件调用
function afterDelFilter(filterId: number) {
  definedTabs.forEach((item, i) => {
    if (item.id === filterId) {
      definedTabs.splice(i, 1)
    }
  })
  selectedTabs.forEach((item, i) => {
    if (item.id === filterId) {
      selectedTabs.splice(i, 1)
    }
  })
  if (filterId === editableTabsValue.value) {
    // 同时选中当前tab中的前面一个或者是后面一个
    const nextTab = selectedTabs[0]
    editableTabsValue.value = nextTab.id
    tabClick() // 删除后，还需要再调查询接口
  }
  currentFilters = currentFilters.filter(
    (item) => item.id !== filterId
  )
  successMsg('删除成功！')
}
function changeFilter() {
  conditionShow.value = !conditionShow.value
  if (props.isSaveLocal) {
    dbData.conditionShow = conditionShow.value
    saveDb()
  } else {
    localStorage.setItem(props.filterType, JSON.stringify(conditionShow.value))
  }
}

function getVal(val: number) {
  return val === 1
}
// 设置某一字段的值
function setFieldValue(field: string, val: any) {
  nextTick(() => {
    filterConditions[field] = val
  })
}
// 暴露方法供父组件调用
defineExpose({
  setFieldValue,
  handleSearch
})

</script>
<style lang="less" scoped>
:deep(.el-tabs__header.is-top) {
  padding-right: 120px;
}
:deep(.el-tabs__item.is-top){
  i.is-icon-close{
    opacity:0;
  }
  &:hover{
    i.is-icon-close{
      opacity:1;
    }
  }
}

.buttonArea {
  position: absolute;
  top: 11px;
  right: 0px;
  display: flex;
  align-items: center;
  font-size: 14px;

  .el-dropdown-link {
    margin-right: 5px;
  }

  .el-dropdown-link.el-popover__reference {
    margin-right: 20px;
  }
}

:deep(.el-form-item--small.el-form-item) {
  margin-bottom: 16px;
}

.filterSelect {
  max-height: 80vh;
  overflow: auto;
}

.border-top {
  border-top: 1px solid #ccc;
  padding-top: 10px
}
.jacp-setting-fields{
  li{
    display: flex;
    align-items: center;
    label{
      flex:1;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }
}
</style>

